package com.yxx.strategy.likeStrategyImpl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yxx.constant.CommonConstant;
import com.yxx.constant.RedisConstant;
import com.yxx.entity.Article;
import com.yxx.mapper.ArticleMapper;
import com.yxx.service.RedisService;
import com.yxx.strategy.LikeStrategy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 文章点赞策略
 * @author yuxiangxun
 * @date 2025/2/8
 * @apiNote
 */
@Service("articleLikeStrategyImpl")
public class ArticleLikeStrategyImpl implements LikeStrategy {

    @Resource
    private RedisService redisService;

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 文章点赞行为
     * @param typeId 文章id
     */
    @Override
    public void like(Integer typeId) {
        // 判断文章是否进入回收站
        Article article = articleMapper.selectOne(new LambdaQueryWrapper<Article>()
                .select(Article::getId, Article::getIsDelete)
                .eq(Article::getId, typeId));
        // 断言，文章进入了回收站，则文章不存在，抛异常
        Assert.isFalse(Objects.isNull(article) || article.getIsDelete().equals(CommonConstant.TRUE),"文章不存在");
        // 文章存在，点赞： user_article_like:userId作为键，文章id作为值，记录用户点赞
        String userLikeArticleKey = RedisConstant.USER_ARTICLE_LIKE + StpUtil.getLoginIdAsInt();
        // 判断是否点赞
        if(redisService.hasSetValue(userLikeArticleKey,typeId)){
            // 点过赞了，那么这一次的点击则是取消点赞的操作，删除用户id中的文章id
            redisService.deleteSet(userLikeArticleKey,typeId);
            // 文章点赞量-1
            redisService.decrHash(RedisConstant.ARTICLE_LIKE_COUNT,typeId.toString(),1L);
        }else {
            // 没有点过赞，那么这一次的点击则是点赞的操作，用户id中添加文章id
            redisService.setSet(userLikeArticleKey,typeId);
            // 文章点赞量+1
            redisService.incrHash(RedisConstant.ARTICLE_LIKE_COUNT,typeId.toString(),1L);
        }
    }
}
